package com.mmall.controller;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IFileService;
import com.mmall.service.SendMailService;
import com.mmall.service.UserService;
import com.mmall.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user/")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SendMailService sendMailService;
    @Autowired
    private IFileService iFileService;

    /**
     * 用户登录
     * @param stuId
     * @param password
     * @return
     */
    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse login(String stuId,String password){
        String md5Pwd = MD5Util.MD5EncodeUtf8(password);

        return userService.login(stuId,md5Pwd);
    }

    /**
     * 个人信息修改
     * @param user
     * @return
     */
    @RequestMapping(value = "update.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse update(User user,String loginToken){
        //调用验证登录方法，把传入的token带入redis看用户信息是否存在
        ServerResponse response = userService.userIsLogin(loginToken);
        if(!response.isSuccess()){    //如果未登录，就返回错误信息
            return response;
        }
        User rUser = (User)response.getData();//缓存中的用户信息
        user.setId(rUser.getId());
        return userService.updateInfo(user,loginToken);
    }

    @RequestMapping(value = "updatePwd.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse updatePwd(String oldPwd,String newPwd,String loginToken){

        //调用验证登录方法，把传入的token带入redis看用户信息是否存在
        ServerResponse response = userService.userIsLogin(loginToken);
        if(!response.isSuccess()){    //如果未登录，就返回错误信息
            return response;
        }
        User user = (User)response.getData();
        return userService.updatePassword(user.getStuId(),oldPwd,newPwd);
    }

    @RequestMapping(value = "sendMail.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse send(String toMail,HttpServletRequest request){

        if(!userService.checkEmail(toMail).isSuccess()){
            return ServerResponse.createByErrorMessage("邮箱未绑定");
        }
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(5 * 60);
        int vCode =(int)((Math.random()*9+1)*100000);
        session.setAttribute(toMail,vCode);
//        sendMailService.sendSimpleMail("密码重置","你的验证码为"+vCode+"(5分钟内有效)-------校园二手平台APP",toMail);
        sendMailService.sendHtmlMail("密码重置","你的验证码为"+vCode+"(5分钟内有效)-------校园二手平台APP",toMail);
        return ServerResponse.cerateBySuccessMessage("已发送");
    }
    @RequestMapping(value = "resetPwd.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse resetPwd(String toMail,String vCode,String pwd,HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session.getAttribute(toMail)==null){
            return ServerResponse.createByErrorMessage("验证码已过期");
        }
        String code = session.getAttribute(toMail).toString();
        if(vCode ==null || !vCode.equals(code)){
            return ServerResponse.createByErrorMessage("验证码错误");
        }
        String md5Pwd = MD5Util.MD5EncodeUtf8(pwd);
        if(userService.resetPwd(toMail,md5Pwd).isSuccess()){
            session.removeAttribute(toMail);    //密码重置后，清除验证码
            return ServerResponse.cerateBySuccessMessage("重置密码成功");
        }
        return ServerResponse.cerateBySuccessMessage("重置密码失败");
    }

    @RequestMapping(value = "logout.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> logout(String stuIdToken){

        return userService.loginOut(stuIdToken);
    }

    @RequestMapping(value = "getUserInfo.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> getUserInfo(String loginToken){

        //调用验证登录方法，把传入的token带入redis看用户信息是否存在
      ServerResponse response = userService.userIsLogin(loginToken);
      if(!response.isSuccess()){    //如果未登录，就返回错误信息
          return response;
      }
      User user = (User)response.getData();
        return ServerResponse.cerateBySuccess("用户获取信息成功",user);
    }

    //更换头像
    @RequestMapping("uploadface.do")
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "file",required = false) MultipartFile file,String stuIdToken,String loginToken,HttpServletRequest request){

//
//        //调用验证登录方法，把传入的token带入redis看用户信息是否存在
//        ServerResponse response = userService.userIsLogin(stuIdToken,loginToken);
//        if(!response.isSuccess()){    //如果未登录，就返回错误信息
//            return response;
//        }
//        User user = (User)response.getData();
//        String path = request.getSession().getServletContext().getRealPath("upload");
//        String targetFileName = iFileService.uploadFile(file,path,Const.IMG_USERFACE);
//
//        if(targetFileName ==null){
//            return ServerResponse.createByErrorMessage("图片上传失败");
//        }
//        user.setUserface(targetFileName);
//        return userService.updateInfo(user,stuIdToken,loginToken);
        return null;
    }

    @RequestMapping("register.do")
    @ResponseBody
    public ServerResponse register(String stuId,String password,String email){
        return userService.register(stuId,password,email);
    }

}
